import React, {FC, useContext, useState} from 'react';
import "./index.less";
import {FormattedMessage, useParams} from "@@/exports";
import * as API from "@/services";
import {useRequest} from "ahooks";
import {Empty, Image, Space, Spin} from "antd";
import HxIcon from "@/components/HxIcon";
import {correspVal} from "@/utils/biz";
import {HxConfigContext} from "@/layouts/HxConfigContext";
import {Link} from "umi";
import default_art_cover from "@/assets/default_art_cover.png";
import HxKwNavs from "@/components/HxKwNavs";
import {HxArticleNormalItem} from "@/components/HxArticleItem";
import HxPagination from "@/components/HxPagination";
import SearchMediaItem from "@/pages/SearchPage/common/SearchMediaItem";
import classNames from "classnames";

interface ExpertDetailProps {
}

const searchTypesItems = [
  {
    key: "article",
    label: <FormattedMessage id="text.article"/>,
    listRequest: API.queryFrontArticlesByEs,
  },
  {
    key: "chart",
    label: <FormattedMessage id="text.chart"/>,
    listRequest: API.queryFrontArticleChartsByEs,
  },
  {
    key: "video",
    label: <FormattedMessage id="text.video"/>,
    listRequest: API.queryFrontArticleVideosByEs,
  }
]

const ExpertDetail: FC<ExpertDetailProps> = (props) => {
  const urlParams = useParams();
  const expertId = urlParams["*"];
  const {isZhCN} = useContext(HxConfigContext)
  const [selectedSearchType, setSelectedSearchType] = useState("article");
  const [selectedOrderBy, setSelectedOrderBy] = useState("RELEVANCE")

  const expertReq = useRequest(() => API.queryFrontAuthor(expertId!), {
    refreshDeps: [expertId],
    ready: !!expertId,
  });

  const assArticlesReq = useRequest((p) => {
    return searchTypesItems.find(t => t.key === selectedSearchType)!.listRequest({
      ...p,
      bizAuthorIds: expertId,
      esOrderType: selectedOrderBy,
    });
  }, {
    refreshDeps: [selectedSearchType, selectedOrderBy]
  })

  const record = expertReq.data?.data;
  const assArticles = assArticlesReq.data?.data || [];

  return (
    <div className={"expert-detail-container"}>
      <div className={"expert-detail-left"}>
        <div className={"expert-detail-intro-content"}>
          <div className={"expert-detail-authro-name"}>
            {correspVal(isZhCN, record?.nameCn, record?.nameEn)}
          </div>
          <div className={"expert-detail-authro-meta"}>
            <Space className={"expert-detail-sp-stats"} size={18}>
              <div><HxIcon type={"hxicon-bianjiwenzhang_huaban"}/> {record?.articleTotal}</div>
              <div><HxIcon type={"hxicon-citing"}/> {(record?.citingArticleNum)}</div>
              <div><HxIcon type={"hxicon-xiazai"}/> {record?.downloadNum}</div>
            </Space>
          </div>
          <div className={"expert-detail-authro-dept"}>
            <FormattedMessage id="expert.authors-dept"/>：{correspVal(isZhCN, record?.addressCn, record?.addressEn)}
          </div>
          <div className={"expert-detail-authro-asso-authors"}>
            <FormattedMessage id="expert.authors-related-to"/>：
            {
              record?.associationAuthorList?.map(au => (
                <Link to={`/expert/${au.id}`} key={au.id} className={"ass-author"}>
                  {correspVal(isZhCN, au?.nameCn, au?.nameEn)}
                </Link>
              ))
            }
          </div>
          <div className={"expert-detail-authro-asso-journals"}>
            <h4><FormattedMessage id="expert.journals-related-to"/></h4>
            <div className={"ass-journals-list"}>
              {
                record?.associationJournalList?.map(jo => (
                  <Link to={`/journal/${jo.id}`} key={jo.id} className={"ass-journal"}>
                    <Image className={"ass-journal-cover"} src={jo?.journalCoverPathUrl} fallback={default_art_cover} preview={false}/>
                    <span className={"ass-journal-name"}>{correspVal(isZhCN, jo?.journalNameCn, jo?.journalNameEn)}</span>
                  </Link>
                ))
              }
            </div>
          </div>
        </div>
      </div>
      <div className={"expert-detail-right"}>
        <div className={"expert-article-list-content"}>
          <HxKwNavs
            value={selectedSearchType}
            onChange={(value) => {
              setSelectedSearchType(value);
            }}
            extra={(
              <Space size={36} className={"es-order-type-options"}>
                <a
                  className={classNames("es-order-type-option", selectedOrderBy === "RELEVANCE" ? "active" : "")}
                  onClick={()=>{
                    setSelectedOrderBy("RELEVANCE");
                  }}
                >
                  <FormattedMessage id="text.sort.relevance"/> <HxIcon type="hxicon-daoxu"/>
                </a>
                <a
                  className={classNames("es-order-type-option", selectedOrderBy === "DATE" ? "active" : "")}
                  onClick={()=>{
                    setSelectedOrderBy("DATE");
                  }}
                >
                  <FormattedMessage id="text.sort.publish-time"/> <HxIcon type="hxicon-daoxu"/>
                </a>
              </Space>
            )}
            items={searchTypesItems}
          >
            <div className={`expert-article-list expert-article-${selectedSearchType}-list`}>
              <Spin spinning={assArticlesReq.loading}>
                <div className={"search-record-inner-list"}>
                  {
                    assArticles.length > 0 ? (
                      assArticles.map((item, index) => {
                        if (selectedSearchType === "article") {
                          return (
                            <HxArticleNormalItem
                              key={item.id}
                              showCover={true}
                              article={item}
                              target={"_blank"}
                              onArticleChange={(article) => {
                                assArticlesReq?.mutate((oldData) => {
                                  return {
                                    ...oldData,
                                    data: oldData!.data.map((item) => {
                                      if (item.id === article.id) {
                                        return {
                                          ...article,
                                        }
                                      }
                                      return item;
                                    })
                                  } as API.RespPageResult<API.FrontArticle>;
                                })
                              }}/>
                          )
                        } else {
                          return (
                            <SearchMediaItem
                              type={selectedSearchType as "chart" | "video"}
                              target={"_blank"}
                              record={item}
                              key={item.figureTableId || item.videoId}
                            />
                          )
                        }
                      })
                    ) : (
                      <Empty/>
                    )
                  }
                </div>
                {
                  !!assArticlesReq.data && (
                    <div className={"hx-pagination-wrapper"}>
                      <HxPagination size="default"
                                    total={assArticlesReq.data?.total}
                                    current={assArticlesReq.data.current}
                                    pageSize={assArticlesReq.data.pageSize}
                                    hideOnSinglePage={false}
                                    onChange={(pageNum, pageSize) => {
                                      assArticlesReq.run({
                                        page: pageNum,
                                        pageSize
                                      })
                                    }}
                      />
                    </div>
                  )
                }
              </Spin>
            </div>
          </HxKwNavs>
        </div>
      </div>
    </div>
  );
};

export default ExpertDetail;
